﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;

namespace WinForm_Mes.Process
{
    public partial class ProcessStepUp : DevExpress.XtraEditors.XtraForm
    {
        public ProcessStepUp()
        {
            InitializeComponent();
            this.IsMdiContainer = false;
            
        }

        private int pageIndex = 1;
        private int pageSize = 10; // 可根据需要调整
        private int total = 0;
        private int PageCount = 0;
        private void simpleButton3_Click(object sender, EventArgs e)
        {

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void ProcessStepUp_Load(object sender, EventArgs e)
        {

        }

        public void LoadData(string process)
        {
            //string context = response.Content.ReadAsStringAsync().Result;
            ProcessStepUpList rootObject = JsonConvert.DeserializeObject<ProcessStepUpList>(process);
            gridControl1.DataSource = rootObject.items;
            total = rootObject.total;
            pageIndex = rootObject.pageIndex;
            pageSize = rootObject.pageSize;//rootObject.pageSize;
            total = rootObject.total;
            PageCount = (int)Math.Ceiling((double)total / pageSize);
            //UpdatePagerLabel();
            labelControl4.Text = $"第{pageIndex}/{PageCount}页，共{total}条数据";
            ConfigureGridView();



        }

        private void ConfigureGridView()
        {
            // 配置列显示
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            gridView1.Columns["ProcessCode"].Caption = "工序编码";
            gridView1.Columns["ProcessName"].Caption = "工序名称";
            gridView1.Columns["PreparationTime"].Caption = "准备时间(分钟)";
            gridView1.Columns["ProductionTime"].Caption = "生产时间(分钟)";
            gridView1.Columns["IsEnabled"].Caption = "是否启用";
            gridView1.Columns["Remark"].Caption = "备注";
            gridView1.Columns["Id"].Caption = "主键ID";

            // 设置列宽自适应
            gridView1.BestFitColumns();

            // 设置其他GridView属性
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;
            //gridView1.OptionsSelection.MultiSelect = false;
        }

        private void gridControl1_Click_1(object sender, EventArgs e)
        {

        }


        private async void GetProcessStepUPClick(object sender, EventArgs e)
        {
            await CheckAndPage();
        }


        public async Task CheckAndPage()
        {
            // 获取查询条件
            string processCode = textEdit1.Text.Trim();
            string processName = textEdit2.Text.Trim();
            //string isEnabled = comboBoxEdit1.SelectedIndex.ToString();

            string isEnabled = comboBoxEdit1.SelectedItem?.ToString();
            if (isEnabled == "请选择") isEnabled = ""; // 不筛选
            else if (isEnabled == "启用") isEnabled = "true";
            else if (isEnabled == "禁用") isEnabled = "false";

            try
            {
                // 创建HttpClient实例
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:5053/");
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                // 构建查询参数
                string queryParams = $"?processCode={processCode}&processName={processName}&isEnabled={isEnabled}&pageIndex={pageIndex}&pageSize={pageSize}";

                // 发送GET请求并获取响应
                HttpResponseMessage response = await client.GetAsync($"api/ProcessManagement/GetProcessStepUpList{queryParams}");

                // 检查响应状态
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    labelControl4.Text = $"第{pageIndex}/{PageCount}页，共{total}条数据";
                    // 加载数据
                    LoadData(jsonContent);
                }
                else
                {
                    MessageBox.Show($"查询数据失败: {response.StatusCode}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生异常: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 添加重置功能
        private void ResetProcessSetUpClick(object sender, EventArgs e)
        {
            // 清空查询条件
            textEdit1.Text = "";
            textEdit2.Text = "";
            comboBoxEdit1.Text = "";
        }

        private void PrevTextClick(object sender, EventArgs e)
        {
            if (pageIndex>1 && pageIndex<=PageCount)
            {
                pageIndex -= 1;
                CheckAndPage();
            }
        }

        private void NextTextClick(object sender, EventArgs e)
        {
            if (pageIndex < PageCount && pageIndex>=1)
            {
                pageIndex += 1;
                CheckAndPage();
            }
        }

        private void AddProcessSetUpClick(object sender, EventArgs e)
        {
            AddProcessForm addprocessform = new AddProcessForm();
            addprocessform.StartPosition = FormStartPosition.CenterParent;
            addprocessform.ShowDialog();
            CheckAndPage();
        }

        // 获取选中的行数据
        private List<Item> GetSelectedItems()
        {
            List<Item> selectedItems = new List<Item>();
            int[] selectedRows = gridView1.GetSelectedRows();
            
            foreach (int rowHandle in selectedRows)
            {
                if (rowHandle >= 0)
                {
                    Item item = gridView1.GetRow(rowHandle) as Item;
                    if (item != null)
                    {
                        selectedItems.Add(item);
                    }
                }
            }
            
            return selectedItems;
        }

        private async void DeleteProcessSetUpClick(object sender, EventArgs e)
        {
            // 获取选中的项目
            var selectedItems = GetSelectedItems();
            
            // 检查是否选中数据
            if (selectedItems.Count == 0)
            {
                MessageBox.Show("请选择要删除的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 检查是否只选中一条数据
            if (selectedItems.Count > 1)
            {
                MessageBox.Show("只能选择一条数据进行删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 确认删除
            var itemToDelete = selectedItems[0];
            if (MessageBox.Show($"确定要删除工序编码为 '{itemToDelete.ProcessCode}' 的数据吗？", 
                "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    // 创建HttpClient实例
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri("http://localhost:5053/");
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                        // 构建要删除的数据对象
                        var deleteData = new { id = itemToDelete.Id };
                        var json = JsonConvert.SerializeObject(deleteData);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        // 发送DELETE请求
                        HttpResponseMessage response = await client.PostAsync($"api/ProcessManagement/DeleteProcessStepUp?id={itemToDelete.Id}", null);

                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // 刷新数据
                            await CheckAndPage();
                        }
                        else
                        {
                            string errorMessage = await response.Content.ReadAsStringAsync();
                            MessageBox.Show($"删除失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除过程中发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // 在现有代码中添加修改按钮事件方法
        private async void EditProcessSetUpClick(object sender, EventArgs e)
        {

           
            // 获取选中的项目
            var selectedItems = GetSelectedItems();
            
            // 检查是否选中数据
            if (selectedItems.Count == 0)
            {
                MessageBox.Show("请选择要修改的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 检查是否只选中一条数据
            if (selectedItems.Count > 1)
            {
                MessageBox.Show("只能选择一条数据进行修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            var itemToEdit = selectedItems[0];
            
            try
            {
                // 调用后端接口获取最新数据
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5053/");
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    
                    // 获取要编辑的数据详情
                    var response = await client.GetAsync($"/api/ProcessManagement/FindProcessStepUp?id={itemToEdit.Id}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<ApiResponse<Item>>(json);
                        var editData = apiResponse.data;

                        // 弹出修改窗口并传递数据
                        UpdateProcessForm editForm = new UpdateProcessForm(editData);
                        editForm.StartPosition = FormStartPosition.CenterParent;
                        
                        if (editForm.ShowDialog() == DialogResult.OK)
                        {
                            // 修改成功后刷新数据
                            await CheckAndPage();
                        }
                    }
                    else
                    {
                        string errorMessage = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"获取数据失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据过程中发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    public class ApiResponse<T>
    {
        public int code { get; set; }
        public string message { get; set; }
        public T data { get; set; }
    }

    
}